﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace XYX.Http.Mvc
{
    /// <summary>
    ///响应返回文本格式
    /// </summary>
    public class ContentResult : ActionResult
    {
        /// <summary>
        /// 响应的内容
        /// </summary>
        public string Content { get; set; }
        /// <summary>
        /// 内容的编码格式
        /// </summary>
        public Encoding ContentEncoding { get; set; } = Encoding.UTF8;


        /// <summary>
        /// 响应的类型
        /// </summary>
        public string ContentType { get; set; }
        /// <summary>
        /// 执行返回结果
        /// </summary>
        /// <param name="response"></param>
        /// <param name="routeData"></param>
        public override void ExecuteResult(HttpListenerResponse response, RouteData routeData)
        {

            if (!string.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "text/plain";
            }
          
            response.SendChunked = true;
            response.ContentEncoding = ContentEncoding;
            response.StatusCode = 200;
            StreamWriter writer = new StreamWriter(response.OutputStream, Encoding.UTF8);
            writer.WriteLine(Content);
            writer.Flush();
            writer.Close();
            response.Close();
        }
    }
}